package com.innovation.ic.cc.base.service.cc.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.innovation.ic.b1b.framework.util.HanziToPinyinUtils;
import com.innovation.ic.b1b.framework.util.HttpUtils;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.innovation.ic.cc.base.handler.cc.AuthenticationUserHandler;
import com.innovation.ic.cc.base.mapper.cc.UserMapper;
import com.innovation.ic.cc.base.model.cc.MapUserRole;
import com.innovation.ic.cc.base.model.cc.Role;
import com.innovation.ic.cc.base.model.cc.User;
import com.innovation.ic.cc.base.model.cc.erp9_pvesiteuser.ParentUsersTopView;
import com.innovation.ic.cc.base.model.cc.erp9_pvesiteuser.UsersTopView;
import com.innovation.ic.cc.base.pojo.UserMainPojo;
import com.innovation.ic.cc.base.pojo.constant.*;
import com.innovation.ic.cc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.cc.base.pojo.constant.handler.RedisStorage;
import com.innovation.ic.cc.base.pojo.constant.model.DefaultUserConstants;
import com.innovation.ic.cc.base.pojo.enums.RedisKeyPrefixEnum;
import com.innovation.ic.cc.base.pojo.variable.AuthenticationUser;
import com.innovation.ic.cc.base.pojo.variable.PageNationPojo;
import com.innovation.ic.cc.base.pojo.variable.RedisRolePojo;
import com.innovation.ic.cc.base.pojo.variable.ServiceResult;
import com.innovation.ic.cc.base.pojo.variable.SubUsersPojo;
import com.innovation.ic.cc.base.pojo.variable.UserPagePojo;
import com.innovation.ic.cc.base.pojo.variable.UsersIdsPojo;
import com.innovation.ic.cc.base.service.ServiceHelper;
import com.innovation.ic.cc.base.service.cc.MyCompanyService;
import com.innovation.ic.cc.base.service.cc.UserService;
import com.innovation.ic.cc.base.vo.login.LoginByUserNameVo;
import com.innovation.ic.cc.base.vo.user.ForgetPasswordVo;
import com.innovation.ic.cc.base.vo.user.UpdatePasswordVo;
import com.innovation.ic.cc.base.vo.user.UsersVo;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Logger log = LoggerFactory.getLogger(ServiceImpl.class);
//    @Resource
//    private UserMapper userMapper;

    @Resource
    private ServiceHelper serviceHelper;

    @Resource
    private MyCompanyService myCompanyService;

    /**
     * 查找所有User对象
     *
     * @return
     */
    @Override
    public ServiceResult<List<User>> findAll() {
        ServiceResult<List<User>> serviceResult = new ServiceResult<List<User>>();

        Wrapper<User> userWrapper = new QueryWrapper<>();
        List<User> userList = baseMapper.selectList(userWrapper);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(userList);
        return serviceResult;
    }

    /**
     * 忘记密码
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<Boolean> forgetPassword(UsersVo usersVo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        //通过手机号获取当前用户信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", usersVo.getPhone());
        User user = baseMapper.selectOne(userQueryWrapper);
        //需要把通过主键获取用户详情缓存清空
        String redisUserNameKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + user.getId();
        serviceHelper.getRedisManager().del(redisUserNameKey);
        ForgetPasswordVo forgetPasswordVo = new ForgetPasswordVo();
        forgetPasswordVo.setPassWord(usersVo.getNewPassword());
        forgetPasswordVo.setPhoneNum(usersVo.getPhone());
        forgetPasswordVo.setCode(usersVo.getCode());
        forgetPasswordVo.setWebSite(DefaultUserConstants.DEFAULT_WEBSITE);
        forgetPasswordVo.setType(DefaultUserConstants.DEFAULT_TYPE);
        // 向erp 传递账号、密码、手机号、验证码
        String passwordData = HttpUtils.sendPostJson(serviceHelper.getErpInterfaceAddressConfig().getErpForgotPasswordUrl(), forgetPasswordVo);
        Object parse = JSONObject.parse(passwordData);
        Map entity = (Map) parse;
        Boolean success = (Boolean) entity.get("success");
        if (success) {//判断当前返回状态
            serviceResult.setSuccess(Boolean.TRUE);
            return serviceResult;
        } else {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage(entity.get("data").toString());
            return serviceResult;
        }
    }

    /**
     * 通过主键获取用户详情
     *
     * @param id
     * @return
     */
    @Override
    public ServiceResult<AuthenticationUser> queryUsers(String id) {
        ServiceResult<AuthenticationUser> serviceResult = new ServiceResult<>();
        //从缓存中获取数据
        String redisKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + id;
        Object redisDepartment = serviceHelper.getRedisManager().get(redisKey);//redis中获取对应数据
        if (redisDepartment == null) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            User user = serviceHelper.getUserMapper().selectOne(queryWrapper);
            if (user == null) {//当前数据并不存在存 缓存为空字符串
                String userRedisKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + id;
                serviceHelper.getRedisManager().set(userRedisKey, RedisStorage.EMPTY_VALUE);
                log.warn("用户不存在");
                serviceResult.setMessage("用户不存在");
                serviceResult.setSuccess(Boolean.FALSE);
                return serviceResult;
            }
            //mysql存在当前数据存入缓存中
            String redisUserIdKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + user.getId();
            String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
            serviceHelper.getRedisManager().set(redisUserIdKey, apiResultJson);
            //封装用户详情
            AuthenticationUser authenticationUser = this.encapsulationUser(user);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(authenticationUser);
            return serviceResult;
        }
        if (redisDepartment.equals(RedisStorage.EMPTY_VALUE)) {//为空字符串或根本不存在redis中数据
            log.warn("用户不存在");
            serviceResult.setMessage("用户不存在");
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
        User user = JSONObject.parseObject((String) redisDepartment, User.class);//反序列化数据
        //封装用户详情
        AuthenticationUser authenticationUser = this.encapsulationUser(user);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(authenticationUser);
        return serviceResult;
    }

    //封装用户详情方法
    private AuthenticationUser encapsulationUser(User user) {
        AuthenticationUser authenticationUser = new AuthenticationUser();
        authenticationUser.setId(user.getId());//用户id
        authenticationUser.setUsername(user.getUserName());// 账号
        authenticationUser.setName(user.getRealName());    // 名称
        authenticationUser.setPosition(String.valueOf(user.getPosition()));// 职位：1表示经理，2表示员工
        authenticationUser.setPhone(user.getPhone());    //手机号
        authenticationUser.setEmail(user.getEmail());//邮箱
        authenticationUser.setStatus(String.valueOf(user.getStatus()));//状态
        Date create = user.getCreateDate();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createDate = simpleDateFormat.format(create);
        authenticationUser.setCreateDate(createDate);//创建日期
        authenticationUser.setEpId(user.getEnterpriseId());//供应商id
        if (StringUtils.isEmpty(user.getFatherId())) {//当前用户是否有主账号
            authenticationUser.setEpName(user.getUserName());//主账号账号
            authenticationUser.setIsMain(1);//是否是主账号
            authenticationUser.setRoleName(UserConstants.ROLE_MAIN);//主账号为默认 数据不存在数据库中
        } else {//表示当前用户是子账号去查主账号信息
            QueryWrapper<User> queryWrapperMain = new QueryWrapper<>();
            queryWrapperMain.eq("id", user.getFatherId());
            User userMain = serviceHelper.getUserMapper().selectOne(queryWrapperMain);//获取主账号
            if (userMain == null) {
                log.warn("因数据异常，子账号绑定主账号数据不存在");
            } else {
                authenticationUser.setEpName(userMain.getRealName());//主账号账号
            }
            authenticationUser.setIsMain(0);//是否是主账号
            authenticationUser.setRoleName(getRoleNames(user.getId()));//子账号的角色名称
        }
        return authenticationUser;
    }

    /**
     * 修改密码
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<Boolean> updatePassword(UsersVo usersVo, AuthenticationUser authenticationUser) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        //用于清空缓存
        String redisUserNameKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + authenticationUser.getId();
        serviceHelper.getRedisManager().del(redisUserNameKey);//redis缓存清空
        UpdatePasswordVo updatePasswordVo = new UpdatePasswordVo();
        updatePasswordVo.setOldPassword(usersVo.getPassword());
        updatePasswordVo.setNewPassword(usersVo.getNewPassword());
        //向erp发送旧密码、新密码
        String data = HttpUtils.sendPostJson(serviceHelper.getLoginConfig().getUpdatePasswordUrl(), updatePasswordVo, usersVo.getToken());
        JSONObject jsonObject = JSON.parseObject(data);
        Boolean success = jsonObject.getBoolean("success");
        if (success.equals(Boolean.FALSE)) {
            serviceResult.setMessage(jsonObject.getString("msg"));
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 修改手机号
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<Map> updatePhone(UsersVo usersVo) throws IOException {
        ServiceResult<Map> serviceResult = new ServiceResult<>();
        UpdateWrapper<User> usersUpdateWrapper = new UpdateWrapper<>();
        usersUpdateWrapper.eq("user_name", usersVo.getUserName());
        User userData = serviceHelper.getUserMapper().selectOne(usersUpdateWrapper);
        ArrayList<String> redisKeyList = new ArrayList<>();//存储所有key用于清空redis缓存
        //清空缓存
        String redisPhoneKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + userData.getPhone();//校验子账号添加时手机号是否重复缓存
        redisKeyList.add(redisPhoneKey);
        String redisUserIdKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + userData.getId();//校验子账号添加时手机号是否重复缓存
        redisKeyList.add(redisUserIdKey);
        serviceHelper.getRedisManager().del(redisKeyList);

        User user = new User();
        user.setPhone(usersVo.getPhone());
        user.setModifyDate(new Date());
        serviceHelper.getUserMapper().update(user, usersUpdateWrapper);
        User usermq = serviceHelper.getUserMapper().selectOne(usersUpdateWrapper);//修改后的数据
        User mqUser = new User();//mq推送消息体(因为不需要多余数据所以封装数据)
        mqUser.setId(usermq.getId());
        mqUser.setPhone(usermq.getPhone());
        mqUser.setModifyDate(usermq.getModifyDate());
        mqUser.setWebSite(DefaultUserConstants.DEFAULT_WEBSITE);
        mqUser.setType(DefaultUserConstants.DEFAULT_TYPE);
        //通过mq向erp中传递消息
        JSONObject json = (JSONObject) JSONObject.toJSON(mqUser);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.CC_ERP_UPDATE_PHONE);
        log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_ERP_UPDATE_PHONE, json.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_TO_ERP_QUEUE_NAME, RabbitMqConstants.CC_ERP_UPDATE_PHONE, null, result.toString().getBytes());
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", usermq.getPhone());
        serviceResult.setResult(map);
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 当前主账号下分页展示子账号信息
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<PageNationPojo<UserPagePojo>> pageUserNew(UsersVo usersVo) {
        com.github.pagehelper.Page<Object> page = PageHelper.startPage(usersVo.getPageNo(), usersVo.getPageSize(), "create_date desc");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //查询 角色
        if (StringUtils.isNotEmpty(usersVo.getRoleId())) {
            Set<String> userRoleIds = getUserRoleId(usersVo.getRoleId());
            if (userRoleIds != null && userRoleIds.size() > 0) {
                queryWrapper.in(User::getId, userRoleIds);
            } else {
                return ServiceResult.ok(PageNationPojo.fromPage(page, null), "查询用户列表数据成功");
            }
        }
        //登入账户
        if (StringUtils.isNotEmpty(usersVo.getUserName())) {
            queryWrapper.like(User::getUserName, usersVo.getUserName());
        }
        //名称
        if (StringUtils.isNotEmpty(usersVo.getRealName())) {
            //如果传递参数为拼音
            if (usersVo.getRealName().matches(ParameterType.pinYin)) {
                queryWrapper.like(User::getPinYin, usersVo.getRealName());
            } else {
                queryWrapper.like(User::getRealName, usersVo.getRealName());
            }
        }
        //职位：1表示经理，2表示员工
        if (usersVo.getPosition() != null) {
            queryWrapper.eq(User::getPosition, usersVo.getPosition());
        }
        //手机号
        if (StringUtils.isNotEmpty(usersVo.getPhone())) {
            queryWrapper.like(User::getPhone, usersVo.getPhone());
        }
        //账号状态
        if (usersVo.getStatus() != null) {
            queryWrapper.eq(User::getStatus, usersVo.getStatus());
        }
        //子账号也需要展示当前所以员工 排除自身
        if (StringUtils.isNotEmpty(usersVo.getFatherId())) {
            queryWrapper.eq(User::getFatherId, usersVo.getFatherId());
        } else {
            //查询子账号
            queryWrapper.eq(User::getFatherId, usersVo.getId());
        }
        List<User> list = baseMapper.selectList(queryWrapper);
        List<UserPagePojo> userPagePojoList = list.stream().map(user -> {
            UserPagePojo userPagePojo = new UserPagePojo();
            BeanUtils.copyProperties(user, userPagePojo);
            userPagePojo.setRoleNames(getRoleNames(user.getId()));
            return userPagePojo;
        }).collect(Collectors.toList());
        return ServiceResult.ok(PageNationPojo.fromPage(page, userPagePojoList), "查询用户列表数据成功");
    }

    /**
     * 获取用户和角色关系的角色名称
     *
     * @param userId
     * @param
     * @return
     */
    private String getRoleNames(String userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        List<MapUserRole> mapUserRoleList = serviceHelper.getMongodbManager().find(query, MapUserRole.class);
        Set<String> list = new HashSet<>(mapUserRoleList.size());
        for (MapUserRole mapUserRole : mapUserRoleList) {
            list.add(mapUserRole.getRoleId());
        }
//        query = new Query(Criteria.where("_id").in(list));
//        List<Role> roleList = serviceHelper.getMongodbManager().find(query, Role.class);
        StringBuffer buffer = new StringBuffer();
        List<Role> roleList = this.selectRedisData(list);
        for (Role role : roleList) {
            buffer.append(role.getName()).append(",");
        }
        if (StringUtils.isEmpty(buffer.toString())) {
            return "";
        }
        return buffer.toString().substring(0, buffer.toString().length() - 1);
    }

    /**
     * 获取用户和角色关系
     *
     * @param roleId
     * @param
     * @return
     */
    private Set<String> getUserRoleId(String roleId) {
        Query query = new Query(Criteria.where("roleId").is(roleId));
        List<MapUserRole> mapUserRoleList = serviceHelper.getMongodbManager().find(query, MapUserRole.class);
        Set<String> list = new HashSet<>();
        for (MapUserRole mapUserRole : mapUserRoleList) {
            list.add(mapUserRole.getUserId());
        }
        return list;
    }

    @Override
    public ServiceResult<User> findByUserId(String userId) {
        ServiceResult<User> serviceResult = new ServiceResult<User>();
        User user = getById(userId);
        serviceResult.setResult(user);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    /**
     * 判断当前数据是否重复
     *
     * @param userData
     * @param key
     * @return
     */
    @Override
    public ServiceResult<Boolean> findData(String userData, String key) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        if (key.equals(UserType.USER_TYPE)) {//如果是账号数据
            //从缓存中获取数据
            String redisKey = RedisKeyPrefixEnum.CHENK_FINDUSERNAME_DATA.getCode() + "_" + userData;
            Object redisDepartment = serviceHelper.getRedisManager().get(redisKey);//redis中获取对应数据
            if (redisDepartment == null) {//redis中不存在反查mysql
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("user_name", userData);
                User user = serviceHelper.getUserMapper().selectOne(userQueryWrapper);//获取到当前用户信息
                if (user == null) {//当前数据并不存在存 缓存为空字符串
                    String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDUSERNAME_DATA.getCode() + "_" + userData;
                    serviceHelper.getRedisManager().set(userRedisKey, RedisStorage.EMPTY_VALUE);
                    serviceResult.setSuccess(Boolean.TRUE);
                    return serviceResult;
                }
                //当前数据存入缓存中
                String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDUSERNAME_DATA.getCode() + "_" + user.getUserName();
                String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(userRedisKey, apiResultJson);
                log.warn("账号已存在，请重新输入");
                serviceResult.setMessage("账号已存在，请重新输入");
                serviceResult.setSuccess(Boolean.FALSE);
                return serviceResult;
            }
            if (redisDepartment.equals(RedisStorage.EMPTY_VALUE)) {//为空字符串或根本不存在redis中数据
                serviceResult.setSuccess(Boolean.TRUE);
                return serviceResult;
            }
            log.warn("账号已存在，请重新输入");
            serviceResult.setMessage("账号已存在，请重新输入");
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        } else if (key.equals(UserType.PHONE_TYPE)) {//如果是手机号数据
            //从缓存中获取数据
            String redisKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + userData;
            Object redisDepartment = serviceHelper.getRedisManager().get(redisKey);//redis中获取对应数据
            if (redisDepartment == null) {//redis中不存在反查mysql
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("phone", userData);
                User user = serviceHelper.getUserMapper().selectOne(userQueryWrapper);
                if (user == null) {//当前数据并不存在存 缓存为空字符串
                    String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + userData;
                    serviceHelper.getRedisManager().set(userRedisKey, RedisStorage.EMPTY_VALUE);
                    serviceResult.setSuccess(Boolean.TRUE);
                    return serviceResult;
                }
                //当前数据存入缓存中
                String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + user.getPhone();
                String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(userRedisKey, apiResultJson);
                log.warn("手机号已被绑定，请重新输入");
                serviceResult.setMessage("手机号已被绑定，请重新输入");
                serviceResult.setSuccess(Boolean.FALSE);
                return serviceResult;
            }
            if (redisDepartment.equals(RedisStorage.EMPTY_VALUE)) {//为空字符串或根本不存在redis中数据
                serviceResult.setSuccess(Boolean.TRUE);
                return serviceResult;
            }
            log.warn("手机号已被绑定，请重新输入");
            serviceResult.setMessage("手机号已被绑定，请重新输入");
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        } else {//如果是邮箱数据
            //从缓存中获取数据
            String redisKey = RedisKeyPrefixEnum.CHENK_FINDEMAIL_DATA.getCode() + "_" + userData;
            Object redisDepartment = serviceHelper.getRedisManager().get(redisKey);//redis中获取对应数据
            if (redisDepartment == null) {//redis中不存在反查mysql
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("email", userData);
                User user = serviceHelper.getUserMapper().selectOne(userQueryWrapper);
                if (user == null) {//当前数据并不存在存 缓存为空字符串
                    String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDEMAIL_DATA.getCode() + "_" + userData;
                    serviceHelper.getRedisManager().set(userRedisKey, RedisStorage.EMPTY_VALUE);
                    serviceResult.setSuccess(Boolean.TRUE);
                    return serviceResult;
                }
                //当前数据存入缓存中
                String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDEMAIL_DATA.getCode() + "_" + user.getEmail();
                String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(userRedisKey, apiResultJson);
                log.warn("邮箱已存在，请重新输入");
                serviceResult.setMessage("邮箱已存在，请重新输入");
                serviceResult.setSuccess(Boolean.FALSE);
                return serviceResult;
            }
            if (redisDepartment.equals(RedisStorage.EMPTY_VALUE)) {//为空字符串或根本不存在redis中数据
                serviceResult.setSuccess(Boolean.TRUE);
                return serviceResult;
            }
            log.warn("邮箱已存在，请重新输入");
            serviceResult.setMessage("邮箱已存在，请重新输入");
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
    }

    /**
     * 新增账号
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<String> saveUser(UsersVo usersVo, String id) throws IOException, ParseException {
        ServiceResult<String> serviceResult = new ServiceResult<>();
        SubUsersPojo userData = new SubUsersPojo();
        userData.setFatherID(id);
        userData.setWebSite(DefaultUserConstants.DEFAULT_WEBSITE);
        userData.setType(DefaultUserConstants.DEFAULT_TYPE);
        userData.setUserName(usersVo.getUserName());
        userData.setPassword(DefaultUserConstants.DEFAULT_PASSWORD);
        userData.setRealName(usersVo.getRealName());
        userData.setPhone(usersVo.getPhone());
        userData.setPosition(usersVo.getPosition().toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = new Date();
        userData.setCreateDate(sdf.format(time));
        userData.setStatus(DefaultUserConstants.DEFAULT_STATUS);
        userData.setEmail(usersVo.getEmail());
        String erpUserData = HttpUtils.sendPostJson(serviceHelper.getUserConfig().getEnterSonUserUrl(), userData);
        Object parse = JSONObject.parse(erpUserData);
        Map entity = (Map) parse;
        String status = entity.get("status").toString().toString();
        if (status.equals(CodeConstants.FASE_CODE)) {//erp 状态码 为500
            String msg = entity.get("msg").toString().toString();//获取erp提示的错误信息
            serviceResult.setMessage(msg);
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
        String data = entity.get("data").toString();
        //转换数据
        SubUsersPojo subUsersPojo = JSON.parseObject(data, SubUsersPojo.class);
        this.bindUserData(subUsersPojo);//进行添加数据
        serviceResult.setMessage(ServiceResult.INSERT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(subUsersPojo.getId());
        return serviceResult;
    }

    /**
     * 绑定参数关联传入mysql中
     *
     * @param subUsersPojo
     * @return
     */
    private void bindUserData(SubUsersPojo subUsersPojo) throws ParseException {
        Date date = new Date();
        User user = new User();
        user.setId(subUsersPojo.getId());//主键
        user.setFatherId(subUsersPojo.getFatherID());//主账号的id，如果为空，则表示这是主账号
        user.setWebSite(subUsersPojo.getWebSite());//站点 1 供应商协同系统、2 芯达通系统
        user.setType(subUsersPojo.getType());//类型（1 卖家[供应商]） Seller Buyer
        user.setUserName(subUsersPojo.getUserName());//登入账户
        user.setPassword(subUsersPojo.getPassword());//密码
        user.setRealName(subUsersPojo.getRealName());//名称
        user.setPinYin(HanziToPinyinUtils.getPinyin(subUsersPojo.getRealName()));//名称拼音
        user.setPhone(subUsersPojo.getPhone());//手机号
        user.setPosition(Integer.valueOf(subUsersPojo.getPosition()));//职位
        String createDate = subUsersPojo.getCreateDate();
        date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(createDate);
        user.setCreateDate(date);//创建时间
        user.setStatus(subUsersPojo.getStatus());//状态
        user.setEmail(subUsersPojo.getEmail());//邮箱
        serviceHelper.getUserMapper().insert(user);
    }

    /**
     * 修改账号信息
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<Boolean> updateUser(UsersVo usersVo) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        UpdateWrapper<User> usersUpdateWrapper = new UpdateWrapper<>();
        usersUpdateWrapper.eq("id", usersVo.getId());
        //获取库中数据
        User userData = baseMapper.selectOne(usersUpdateWrapper);//获取到当前用户数据 进行所有缓存清空
        List<String> redisUserList = this.deleteRedisUser(userData);//返回所有需要清空缓存的key
        serviceHelper.getRedisManager().del(redisUserList);
        User user = new User();
        user.setRealName(usersVo.getRealName());
        user.setPhone(usersVo.getPhone());
        user.setEmail(usersVo.getEmail());
        user.setPosition(usersVo.getPosition());
        user.setModifyDate(new Date());
        serviceHelper.getUserMapper().update(user, usersUpdateWrapper);
        User usermq = serviceHelper.getUserMapper().selectOne(usersUpdateWrapper);
        //通过mq向erp中传递消息
        JSONObject json = (JSONObject) JSONObject.toJSON(usermq);
        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.CC_ERP_ADD_SUBUSERS);
        log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_ERP_ADD_SUBUSERS, json.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_TO_ERP_QUEUE_NAME, RabbitMqConstants.CC_ERP_ADD_SUBUSERS, null, result.toString().getBytes());
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    private List<String> deleteRedisUser(User user) {//删除所有缓存key
        List<String> list = new ArrayList<>();//存放所有key
        String redisUserNameKey = RedisKeyPrefixEnum.CHENK_FINDUSERNAME_DATA.getCode() + "_" + user.getUserName();//校验子账号添加时账号是否重复缓存
        list.add(redisUserNameKey);
        String redisPhoneKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + user.getPhone();//校验子账号添加时手机号是否重复缓存
        list.add(redisPhoneKey);
        String redisEmailKey = RedisKeyPrefixEnum.CHENK_FINDEMAIL_DATA.getCode() + "_" + user.getEmail();//校验子账号添加时邮箱是否重复缓存
        list.add(redisEmailKey);
        String redisUserIdKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + user.getId();//校验子账号添加时邮箱是否重复缓存
        list.add(redisUserIdKey);
        return list;
    }

    /**
     * 重置密码
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<Boolean> resetPassword(UsersVo usersVo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        //清空 主键查询账号详情缓存
        String redisUserNameKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + usersVo.getId();
        serviceHelper.getRedisManager().del(redisUserNameKey);//redis缓存清空
        String passwordData = HttpUtils.erpSendPost(serviceHelper.getLoginConfig().getResetPassword(), usersVo.getId(), usersVo.getToken());
        if (!StringUtils.isEmpty(passwordData)) {
            serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            return serviceResult;
        } else {
            serviceResult.setMessage(ServiceResult.UPDATE_FAIL);
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
    }

    /**
     * 账号状态更改
     *
     * @param usersVo
     * @return
     */
    @Override
    public void updateStatus(UsersVo usersVo) {
        try {
            List<String> redisKeyList = new ArrayList<>();//存储redis缓存中key 用于清空缓存
            UsersIdsPojo usersIdsPojo = new UsersIdsPojo();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String time = df.format(new Date());// new Date()为获取当前系统时间
//        Date date = df.parse(Time);
            String id = usersVo.getId();
            String[] ids = id.split(",");
            for (String userId : ids) {//清空所有缓存数据
                String redisUserNameKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + userId;
                redisKeyList.add(redisUserNameKey);
            }
            serviceHelper.getRedisManager().del(redisKeyList);//redis缓存清空
            //进行修改
            serviceHelper.getUserMapper().updateStatus(time, usersVo.getStatus(), ids);
//            //当前修改的数据通过mq传递erp
//            List<User> statusData = userMapper.selectIds(ids);
            usersIdsPojo.setIds(Arrays.asList(ids));//mq发送账号主键
            usersIdsPojo.setStatus(usersVo.getStatus());//mq发送账号状态
            usersIdsPojo.setWebSite(DefaultUserConstants.DEFAULT_WEBSITE);
            usersIdsPojo.setType(DefaultUserConstants.DEFAULT_TYPE);
            JSONObject json = (JSONObject) JSONObject.toJSON(usersIdsPojo);
//            String s = JSONObject.toJSONString(usersIdsPojo);
//            JSONArray json = JSONObject.parseArray(s);
//            JSONObject json = (JSONObject) JSONObject.toJSON(statusData);
//            JSONObject object = new JSONObject();
//            object.put("list",json);
            // 包装发送到rabbitmq的消息内容
            JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.CC_ERP_ENABLE_SUBUSERS);
            log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_ERP_ENABLE_SUBUSERS, json.toString());
            serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.CC_ERP_EXCHANGE, RabbitMqConstants.CC_TO_ERP_QUEUE_NAME, RabbitMqConstants.CC_ERP_ENABLE_SUBUSERS, null, result.toString().getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化校验相关所有数据
     *
     * @return
     */
    @Override
    @Autowired
    public void initCheckData() {
        // 删除redis中的校验相关数据
        Boolean deleteUserNameResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.CHENK_FINDUSERNAME_DATA.getCode() + "*");
        Boolean deletePhoneResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "*");
        Boolean deleteEmailResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.CHENK_FINDEMAIL_DATA.getCode() + "*");
        if (deleteUserNameResult) {
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.CHENK_FINDUSERNAME_DATA.getCode());
        }
        if (deletePhoneResult) {
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode());
        }
        if (deleteEmailResult) {
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.CHENK_FINDEMAIL_DATA.getCode());
        }
        //获取user表所有数据
        List<User> userList = baseMapper.selectList(null);
        //分别 账号 邮箱 手机号 缓存各存遍
        for (User user : userList) {
            if (!StringUtils.isEmpty(user.getUserName())) {//必须保证账号不为空
                String redisKey = RedisKeyPrefixEnum.CHENK_FINDUSERNAME_DATA.getCode() + "_" + user.getUserName();
                String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(redisKey, apiResultJson);
            }
            if (!StringUtils.isEmpty(user.getEmail())) {//必须保证邮箱不为空
                String redisKey = RedisKeyPrefixEnum.CHENK_FINDEMAIL_DATA.getCode() + "_" + user.getEmail();
                String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(redisKey, apiResultJson);
            }
            if (!StringUtils.isEmpty(user.getPhone())) {//必须保证手机号不为空
                String redisKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + user.getPhone();
                String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(redisKey, apiResultJson);
            }
        }
    }

    /**
     * 判断当前密码数据是否重复
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<Boolean> findPassWord(UsersVo usersVo) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        String loginData = HttpUtils.doPostTestTwo(serviceHelper.getLoginConfig().getUrl(), JSON.toJSONString(usersVo));
        JSONObject loginDatas = JSONObject.parseObject(loginData);
        Object status = loginDatas.get(Constants.STATUS_);
        if (status.equals(HttpStatus.HTTP_OK)) {
            serviceResult.setSuccess(Boolean.TRUE);
            return serviceResult;
        } else {
            log.warn("密码有误，请重新输入");
            serviceResult.setMessage("密码有误，请重新输入");
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
    }

    /**
     * 判断手机号是否不正确
     *
     * @param usersVo
     * @return
     */
    @Override
    public ServiceResult<Boolean> findAccountPhone(UsersVo usersVo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        //从缓存中获取数据
        String redisKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + usersVo.getPhone();
        Object redisDepartment = serviceHelper.getRedisManager().get(redisKey);//redis中获取对应数据
        if (redisDepartment == null) {//redis中不存在反查mysql
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("phone", usersVo.getPhone());
            User user = serviceHelper.getUserMapper().selectOne(userQueryWrapper);
            if (user == null) {//当前数据并不存在存 缓存为空字符串
                String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + usersVo.getPhone();
                serviceHelper.getRedisManager().set(userRedisKey, RedisStorage.EMPTY_VALUE);
                log.warn("手机号不存在，请重新输入");
                serviceResult.setMessage("手机号不存在，请重新输入");
                serviceResult.setSuccess(Boolean.FALSE);
                return serviceResult;
            }
            //当前数据存入缓存中
            String userRedisKey = RedisKeyPrefixEnum.CHENK_FINDPHONE_DATA.getCode() + "_" + user.getPhone();
            String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
            serviceHelper.getRedisManager().set(userRedisKey, apiResultJson);
            serviceResult.setSuccess(Boolean.TRUE);
            return serviceResult;
        }
        if (redisDepartment.equals(RedisStorage.EMPTY_VALUE)) {//为空字符串或根本不存在redis中数据
            log.warn("手机号不存在，请重新输入");
            serviceResult.setMessage("手机号不存在，请重新输入");
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 初始化用户相关所有数据
     *
     * @return
     */
    @Override
    @Autowired
    public void initUserData() {
        // 删除redis中的主键相关数据
        Boolean deleteResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "*");
        if (deleteResult) {
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.USER_USERID_DATA.getCode());
        }
        //获取user表所有数据
        List<User> userList = baseMapper.selectList(null);
        //账号当做key 手机存入redis中
        for (User user : userList) {
            String redisKey = RedisKeyPrefixEnum.USER_USERID_DATA.getCode() + "_" + user.getId();
            String apiResultJson = JSONObject.toJSONString(user, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
            serviceHelper.getRedisManager().set(redisKey, apiResultJson);
        }
    }

    private List<Role> selectRedisData(Set<String> roleListId) {
        List<Role> roles = new ArrayList<>();//存结果集合
        for (String roleId : roleListId) {//批量拼接 key
            String redisKey = RedisKeyPrefixEnum.ROLE_ID_DATA.getCode() + "_" + roleId;
            Object redisDepartment = serviceHelper.getRedisManager().get(redisKey);//redis中获取对应数据
            if (redisDepartment == null) {//不存在去数据库中查一下
                Query queryRole = Query.query(Criteria.where("_id").is(roleId));
                //获取对应的角色信息
                Role role = serviceHelper.getMongodbManager().findOne(queryRole, Role.class);
                if (role == null) {//数据库不存在存入缓存 避免重复对数据库添加压力
                    String roleRedisKey = RedisKeyPrefixEnum.ROLE_ID_DATA.getCode() + "_" + roleId;
                    serviceHelper.getRedisManager().set(roleRedisKey, RedisStorage.EMPTY_VALUE);
                    continue;
                }
                RedisRolePojo redisRolePojo = this.packaRedisRoleData(role);
                String rolekey = RedisKeyPrefixEnum.ROLE_ID_DATA.getCode() + "_" + redisRolePojo.get_id();
                String apiResultJson = JSONObject.toJSONString(redisRolePojo, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(rolekey, apiResultJson);
                roles.add(role);
                continue;
            }
            if (RedisStorage.EMPTY_VALUE.equals(redisDepartment)) {//数据库中没此数据
                continue;
            }
            RedisRolePojo redisRolePojo = JSONObject.parseObject((String) redisDepartment, RedisRolePojo.class);//反序列化
            Role role = new Role();
            role.set_id(new ObjectId(redisRolePojo.get_id()));
            role.setName(redisRolePojo.getName());
            role.setAvailable(redisRolePojo.getAvailable());
            role.setCreateTime(redisRolePojo.getCreateTime());
            role.setMenuList(redisRolePojo.getMenuList());
            role.setUpdateTime(redisRolePojo.getUpdateTime());
            role.setCreatorId(redisRolePojo.getCreatorId());
            roles.add(role);
            continue;
        }
        return roles;
    }

    private RedisRolePojo packaRedisRoleData(Role role) {  //封装统一对象存入redis
        RedisRolePojo redisRolePojo = new RedisRolePojo();
        redisRolePojo.set_id(String.valueOf(role.get_id()));
        redisRolePojo.setAvailable(role.getAvailable());
        redisRolePojo.setCreateTime(role.getCreateTime());
        redisRolePojo.setMenuList(role.getMenuList());
        redisRolePojo.setName(role.getName());
        redisRolePojo.setUpdateTime(role.getUpdateTime());
        redisRolePojo.setCreatorId(role.getCreatorId());
        return redisRolePojo;
    }

    /**
     * 先清空 MySQL中users主账号
     *
     * @param map
     * @return
     */
    @Override
    public void batchDelete(Map<String, Object> map) {
        serviceHelper.getUserMapper().deleteByMap(map);
    }

    /**
     * 把sql server中数据同步到MySQL中user表中
     *
     * @param userList
     */
    @Override
    public void insertAllNew(List<ParentUsersTopView> userList) {
        List<User> users = userList.stream().map(parentUsersTopView -> {
            User user = new User();
            BeanUtils.copyProperties(parentUsersTopView, user);
            user.setPinYin(HanziToPinyinUtils.getPinyin(parentUsersTopView.getRealName()));
            if (StringUtils.isNotEmpty(parentUsersTopView.getPosition())) {
                user.setPosition(Integer.valueOf(parentUsersTopView.getPosition()));
            }
            return user;
        }).collect(Collectors.toList());
        Integer integer = serviceHelper.getUserMapper().insertBatchSomeColumn(users);
        System.out.println("插入user:" + integer + "条数据");
    }

    /**
     * 把sql server中数据同步到MySQL中user表中
     *
     * @param userList
     * @return
     */
    @Override
    public void insertAll(List<ParentUsersTopView> userList) {
        serviceHelper.getUserMapper().insertUserList(userList);
    }

    /**
     * 监听主账号新增/修改
     *
     * @param userMainPojo sqlservice中相关数据
     */
    @Override
    public void handleModelAddUsersMqMsg(UserMainPojo userMainPojo) {
        //去mysql中查询一下当前数据是否存在(存在修改/不存在添加)
        User user = findExistence(userMainPojo);
        if (user == null) {
            User userdata = new User();
            userdata.setId(userMainPojo.getId());
            userdata.setWebSite(userMainPojo.getWebSite());
            userdata.setEnterpriseId(userMainPojo.getEnterpriseId());
            userdata.setEnterpriseName(userMainPojo.getEnterpriseName());
            userdata.setType(userMainPojo.getType());
            userdata.setUserName(userMainPojo.getUserName());
            userdata.setPassword(userMainPojo.getPassword());
            userdata.setRealName(userMainPojo.getRealName());
            userdata.setPinYin(HanziToPinyinUtils.getPinyin(userMainPojo.getRealName()));//中文转拼音
            userdata.setPhone(userMainPojo.getPhone());
            userdata.setEmail(userMainPojo.getEmail());
            userdata.setCreateDate(userMainPojo.getCreateDate());
            userdata.setStatus(DefaultUserConstants.DEFAULT_STATUS);
            //添加我的公司关联
            myCompanyService.addUserRelation(userdata);
            serviceHelper.getUserMapper().insert(userdata);
        } else {
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.eq("id", userMainPojo.getId());
            User userdata = new User();
            userdata.setWebSite(userMainPojo.getWebSite());
            userdata.setEnterpriseId(userMainPojo.getEnterpriseId());
            userdata.setEnterpriseName(userMainPojo.getEnterpriseName());
            userdata.setType(userMainPojo.getType());
            userdata.setPassword(userMainPojo.getPassword());
            userdata.setRealName(userMainPojo.getRealName());
            userdata.setPinYin(HanziToPinyinUtils.getPinyin(userMainPojo.getRealName()));//中文转拼音
            userdata.setPhone(userMainPojo.getPhone());
            userdata.setEmail(userMainPojo.getEmail());
            userdata.setModifyDate(userMainPojo.getModifyDate());
            serviceHelper.getUserMapper().update(userdata, userUpdateWrapper);
        }
    }


    /**
     * 判断mysql中是否有当前数据
     *
     * @param userMainPojo sqlservice中相关数据
     */
    private User findExistence(UserMainPojo userMainPojo) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id", userMainPojo.getId());
        User user = serviceHelper.getUserMapper().selectOne(userQueryWrapper);
        if (user == null) {
            return null;
        }
        //清空所有redis缓存
        List<String> redisKeyList = this.deleteRedisUser(user);
        serviceHelper.getRedisManager().del(redisKeyList);//redis缓存清空
        return user;
    }

    /**
     * 监听密码被重置
     *
     * @param usersTopView usersTopView
     */
    @Override
    public void handleModelUpdatePassWordMqMsg(UsersTopView usersTopView) {
        User user = new User();
        user.setPassword(usersTopView.getPassword());
        user.setModifyDate(new Date());
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id", usersTopView.getId());
        serviceHelper.getUserMapper().update(user, userUpdateWrapper);
    }

    /**
     * 监听主账号状态
     *
     * @param userMainPojo sqlservice中相关数据
     */
    @Override
    public void handleModelUpdateUsersMqMsg(UserMainPojo userMainPojo) {
        //去mysql中查询一下当前数据是否存在(存在修改/不存在添加)
        User user = findExistence(userMainPojo);
        if (user == null) {
            log.info("监听主账号删除中mysql当前没有此请求数据");
            return;
        } else {
            //通过id 去修改账号状态
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.eq("id", userMainPojo.getId()).or().eq("father_id", userMainPojo.getId());
            User userDelete = new User();
            userDelete.setStatus(userMainPojo.getStatus());
            userDelete.setModifyDate(userMainPojo.getModifyDate());
            serviceHelper.getUserMapper().update(userDelete, userUpdateWrapper);
        }
    }

    /**
     * 通过账号密码登录
     * @param loginByUserNameVo 通过账号密码登录接口的vo类
     * @return 返回登录结果
     */
    @Override
    public ServiceResult<AuthenticationUser> loginByUsername(LoginByUserNameVo loginByUserNameVo) throws IOException {
        String userName = loginByUserNameVo.getUserName();

        // 判断输入的用户名是否为手机号
        boolean judgeResult = Validator.isMobile(userName);
        if (judgeResult) {
            // 根据手机号查询账号
            List<String> list = serviceHelper.getUserMapper().selectAccountByPhoneNumber(userName);
            if (list != null && list.size() == 1) {
                loginByUserNameVo.setUserName(list.get(0));
            }
        }

        String token;
        ServiceResult<AuthenticationUser> serviceResult = new ServiceResult<>();
        // 通过用户名密码登录并获取token
        String loginData = HttpUtils.doPostTestTwo(serviceHelper.getLoginConfig().getUrl(), JSON.toJSONString(loginByUserNameVo));
        log.info("调用接口【{}】的返回值为：{}", serviceHelper.getLoginConfig().getUrl(), loginData);
        JSONObject loginDatas = JSONObject.parseObject(loginData);
        Object status = loginDatas.get(Constants.STATUS_);
        if (status.equals(HttpStatus.HTTP_OK)) {
            log.info("通过erp接口获取token成功");
            AuthenticationUser authenticationUser = new AuthenticationUser();
            JSONObject data = (JSONObject) loginDatas.get(LoginConstants.DATA);
            if (data != null) {
                token = (String) data.get(LoginConstants.TOKEN);

                // 将token对象转换为接收用户信息vo类对象
                authenticationUser = AuthenticationUserHandler.toAuthenticationUser(token);

                // 我的公司名称列表
                ServiceResult<List<String>> myCompanyNameListServiceResult = myCompanyService.findByEpId(authenticationUser.getEpId());
                if (null != myCompanyNameListServiceResult && null != myCompanyNameListServiceResult.getResult()) {
                    authenticationUser.setMyCompanyNameList(myCompanyNameListServiceResult.getResult());
                }
            }
            serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(authenticationUser);
            return serviceResult;
        } else {
            log.warn("通过erp接口获取token失败,erp返回内容:[{}]", loginData);
            String msg = (String) loginDatas.get(Constants.MSG_);//erp实时返回错误消息体
            serviceResult.setMessage(msg);
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
    }
}
